package com.anche.cywebnew.Controller.exchangeManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anche.cywebnew.DAO.configManager.SysCodeMapper;
import com.anche.cywebnew.DAO.enchangeManager.MessageLogMapper;
import com.anche.cywebnew.DAO.enchangeManager.SysOrganMapper;
import com.anche.cywebnew.Pojo.exchangeManager.YyDataBase;
import com.anche.cywebnew.Pojo.exchangeManager.message.MessageLog;
import com.anche.cywebnew.Pojo.exchangeManager.request.JsonRequest;
import com.anche.cywebnew.Pojo.exchangeManager.request.OperationWrite;
import com.anche.cywebnew.Pojo.exchangeManager.resconnect.DataConnect;
import com.anche.cywebnew.Pojo.exchangeManager.resconnect.ResConnectJson;
import com.anche.cywebnew.Pojo.exchangeManager.resconnect.ResultConnect;
import com.anche.cywebnew.Pojo.exchangeManager.response.DataJson;
import com.anche.cywebnew.Pojo.exchangeManager.response.FieldValues;
import com.anche.cywebnew.Pojo.exchangeManager.resultData.Result;
import com.anche.cywebnew.Pojo.exchangeManager.resultData.Result2;
import com.anche.cywebnew.Pojo.exchangeManager.resultData.Result3;
import com.anche.cywebnew.Service.exchangeManager.DataService;
import com.anche.cywebnew.Utils.query.HttpUtil;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;


@RestController
public class DataController extends BaseController{

    @Autowired
    DataService dataService;

    @Value("${url.message}")
    private String messagelurl;

    @Value("${url.token}")
    private  String tokenUrl;

    @Value("${url.send}")
    private  String sendUrl;

    @Autowired
    private SysOrganMapper sysOrganMapper;

    @Autowired
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private MessageLogMapper messageLogMapper;

    private static final Logger logger = LoggerFactory.getLogger(DataController.class);


    @PostMapping("/gaservice")
    public Object handlePostRequest(@RequestBody JsonRequest jsonRequest) {
        String method = jsonRequest.getMethod();
        if (method.equals("connect")){
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String date = df.format(new Date());
            String code = jsonRequest.getParams().getData().getAppId();

            ResConnectJson json = new ResConnectJson();
            json.setJsonrpc("2.0");
            json.setId("1");
            ResultConnect result1 = new ResultConnect();
            result1.setCode("1");
            result1.setMsg("ok");

            DataConnect data = new DataConnect();
            data.setAppId(code);
            data.setTimestamp(date);
            data.setNonce("QswduIyb");
            data.setSessionId("e68f26bb70ab41b8a9fa2a37b34ab1bc");

            result1.setData(data);
            result1.setSign("1qqqqwwwwwwwwwwwwww");

            json.setResult(result1);
            return json;
        }
        if (method.equals("query")){
            String ok = jsonRequest.getParams().getData().getDataObjId();
            List<YyDataBase> yyDataBases = new ArrayList<>();
            String json="";
            yyDataBases = dataService.selectList();

            if (yyDataBases.size()>0){
                for (YyDataBase item : yyDataBases){
                    item.setYzxzsnr(null);
                }

                json = JSON.toJSONString(yyDataBases);

                Gson gson = new Gson();
                String json1 = gson.toJson(yyDataBases);


                List<YyDataBase> list = yyDataBases;

                for (YyDataBase yyDataBase: list){
                    yyDataBase.setStatus("1");
                    dataService.updateOne(yyDataBase);
                }
                logger.info("返回数据成功!");
                return rendSuccess(json1);
            }else {
                return rendSuccess(null);
            }
        }
        else {
            logger.info("获取到添加内容为:"+jsonRequest.getParams().getData().getOperations().toString());
            String json ="";

            List<OperationWrite> operationWrites = new ArrayList<>();
            operationWrites = jsonRequest.getParams().getData().getOperations();
            List<DataJson> data = new ArrayList<>();
            List<FieldValues> fieldValues = new ArrayList<>();
            for (OperationWrite item : operationWrites){
                 data = item.getData();
            }
            for (DataJson item : data){
                fieldValues = item.getFieldValues();
            }
            for (FieldValues item : fieldValues){
                if (item.getField().equals("data")){
                    json = item.getValue();
                }
            }
            Gson gson = new Gson();
            YyDataBase yyDataBase = gson.fromJson(json, YyDataBase.class);
            int count = 0;
            try {
                String exit = dataService.selectDataBase(yyDataBase);
                if (exit.equals("error")){
                    int i = dataService.updateOne(yyDataBase);
                    System.out.println(i);
                    count = 3;
                }else {
                    count = dataService.insertOne(yyDataBase);
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("添加预约信息异常:"+e.getMessage());
            }
            if (count == 1) {
                logger.info("添加预约信息成功");
                return rendSuccess2("添加成功");
            }else if (count == 3){
                logger.info("更新数据成功");
                //2023.10.07 新增流水爽约推送短信功能
                if (yyDataBase.getLszt().equals("AE2")){
                    try {
                        SendMessageHttp(yyDataBase);
                    } catch (Exception e) {
                        logger.info("发送短信失败");
                    }
                }

                return rendSuccess2("更新成功");
            }else {
                logger.info("添加预约信息失败");
                return rendError2("添加失败");
            }
        }
    }

    @RequestMapping("/zwquery")
    public String handlePostRequest3(){

        Result3 result3 = new Result3();
        Gson gson =new Gson();
        String json = null;

        List<YyDataBase> list = dataService.selectList2();

        List<YyDataBase> list1 = list;
        for (YyDataBase data : list1){
            data.setStatus("1");
            dataService.updateOne(data);
        }
        if (list.size()>0) {
            result3.setCode(1);
            result3.setData(list);
            result3.setMsg("success");
             json = gson.toJson(result3);
        }else {
            result3.setCode(0);
            result3.setData(null);
            result3.setMsg("failed");
            json = gson.toJson(result3);
        }
        return json;
    }

    @RequestMapping("/zwwrite")
    public Result handlePostRequest4(@RequestBody Result2 result){
        String json=JSON.toJSONString(result.getData());
        Gson gson = new Gson();
        YyDataBase data = gson.fromJson(json,YyDataBase.class);
        logger.info("接收到专网写入流水:"+data.getCylsh()+"流水状态:"+data.getLszt());
        //2023.09.26 新增处理今日晚上八点后仍为取出号牌柜中的号牌  推送客户短信处理
        try {
            if (result.getCode() == 8){
                SendMessageHttp(data);
                return Result.success("发送短信成功");
            }else if (result.getCode() == 7){
                //2023.10.07 新增else判断如果code为7的话无号牌业务的制证完成
                // 此处为无牌业务取证完成单独推送 设定单独流水状态发送相应的信息 无牌业务的取证完成流水状态就是有牌业务放入号牌柜的流水状态
                data.setLszt("D11A");
                SendMessageHttp(data);
                return Result.success("发送短信成功");
            }else if (result.getCode() == 6){
                //2023.10.07 新增else判断如果code为6的话就是号牌柜领取成功
                data.setLszt("D13");
                SendMessageHttp(data);
                return Result.success("发送短信成功");
            }
        }catch (Exception e) {
            return Result.failed(404,"发送短信失败");
        }
        // 创建日期时间格式化器
        try {
            String time = data.getBookingDate().substring(0,data.getBookingDate().indexOf(","));
            DateTimeFormatter inputFormatter = null;
            if (time.length()>5) {
                inputFormatter = DateTimeFormatter.ofPattern("MMM dd, yyyy hh:mm:ss a", Locale.ENGLISH);
            }else {
                inputFormatter = DateTimeFormatter.ofPattern("MMM d, yyyy hh:mm:ss a", Locale.ENGLISH);
            }
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 解析输入日期字符串
            LocalDate date = LocalDate.parse(data.getBookingDate(), inputFormatter);

            // 格式化输出日期字符串
            String outputDate = date.format(outputFormatter);

            data.setBookingDate(outputDate);
        }catch (Exception e){
            e.printStackTrace();
            logger.info("获取专网bookingDate的时间转换有错");
        }
        int count = dataService.updateOne(data);
        if (count>0){
            //2023.09.22新增需求  根据流水状态的判断进行短信推送功能  预约成功/受理成功/受理失败/制证完成(无牌业务)/放入号牌柜完成(制证、制牌完成)
            String lszt = data.getLszt();
            if (lszt.contains("A03") || lszt.contains("D01") || lszt.contains("DE1")
                   || lszt.contains("D07") || lszt.contains("D11")) {
                try {
                    logger.info("开始进行信息推送:"+data.getCylsh());
//                    String message = SendMessage(data);
                    String message = SendMessageHttp(data);
                    logger.info("短信推送结果: " + message);
                } catch (Exception e) {
                    logger.info("短信推送失败,失败原因:" + e.getMessage());
                }
            }
            return Result.success("更新成功");
        }else {
            return Result.failed(0,"更新失败");
        }
    }

    //2023.12.12更新短信发送方式,采用HTTP发送短信
    private String SendMessageHttp(YyDataBase data) throws Exception{
        String resultStr = "";
        logger.info("开始获取短信token...");
        String token = getToken("jiaojingzhidui", "jjzd@2023");
        logger.info("获取短信token为:"+token);
        String context = editContext(data);
        logger.info("开始编辑短信内容为:" + context);

        //查询发送次短信次数达到上限值
        int messagenum = dataService.selectMessageNumByCylsh(data.getCylsh());

        //查询上次短信推送的状态
        String scdxts = dataService.selectMessageStatusByCylsh(data.getCylsh());

        if (messagenum<15  && !data.getLszt().equals(scdxts)) {
            logger.info("开始发送短信...");
            resultStr = sendSms(token, data.getPhonenum(), context, "9513110190");
        }else if (scdxts.equals(data.getLszt())){
            resultStr = "失败,流水状态重复推送";
        }else {
            resultStr = "失败,发送短信次数已达上限";
        }
        //如果返回不为空的话则默认发送成功,记录发送次数防止重复发送短信
        if (resultStr.contains("发送成功")){
            messagenum=messagenum+1;
            dataService.updateMessageNumByCylsh(data.getCylsh(),messagenum,data.getLszt());
        }

        //新增记录发送短信日志功能
        MessageLog messageLog = new MessageLog();
        messageLog.setId(UUID.randomUUID().toString().replaceAll("-",""));
        messageLog.setCylsh(data.getCylsh());
        messageLog.setLszt(data.getLszt());
        messageLog.setPhone(data.getPhonenum());
        messageLog.setContext(context);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(date);
        messageLog.setTime(time);
        messageLog.setResult(resultStr);
        try {
            dataService.insetMessageLog(messageLog);
        }catch (Exception e){
            logger.info("添加短信日志异常:"+e.getMessage());
        }

        return  resultStr;
    }


    private String editContext(YyDataBase yyDataBase) {
        String lszt = yyDataBase.getLszt();
        String message ="";
        String username = yyDataBase.getUsername();
        String clsbdh = yyDataBase.getClsbdh().substring(yyDataBase.getClsbdh().length()-4);
        String clpp =yyDataBase.getClpp();
        if (clpp==null){
            clpp="";
        }
        String ywlx = sysCodeMapper.getValueByNameAndCode(yyDataBase.getYwlx(),"业务类型");
        String cylsh = yyDataBase.getCylsh();
        String date =yyDataBase.getBookingDate()+yyDataBase.getBookingTime();
        String organ = sysOrganMapper.getOrganNameByOrgan(yyDataBase.getOrgan());
        String hpgkl = yyDataBase.getHpgkl();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());

        //2023.09.27 处理特殊情况 制证无牌业务类型为:非注册登记A,转入业务I和变更业务(D)的换发新能源号牌(E)的业务
        if (yyDataBase.getYwlx().equals("A")||yyDataBase.getYwlx().equals("I")|| (yyDataBase.getYwlx().equals("D")&& yyDataBase.getYwyy().equals("E"))){
            // 此处为正常有牌业务 流水状态不需要处理
        }else {
            // 此处为无牌业务制证完成单独推送 设定单独流水状态发送相应的信息 前提必须为制证完成
            if ("D07".equals(lszt)){
                lszt = "D07A";
            }
        }

        switch (lszt){
            // 预约成功推送
            case "A03":
                message = "【机动车查验预约】尊敬的"+username+"用户，您的车架号尾号为【"+ clsbdh +"】的【"+ clpp +"】爱车已完成"+ywlx+"业务的预登记，业务流水号为"+cylsh+"，请于"+date+"前往"+organ+"办理。现场业务流程：进场后请先选择大车/小车预约通道，并出示预约二维码通过蓝色自助机刷码验证，进入系统自动分配的查验通道，VIN码免费拓印（如需要），在查验工位完成查验，现场提交登记受理资料，停车到业务大厅完成缴费（线上或窗口）、选号（12123预选号或选号自助机），休息等待牌证领取通知，领取牌证、现场评价，免费安装号牌。";
                break;
            // 受理完成推送
            case "D01":
                message = "【机动车查验预约】尊敬的"+username+"用户，您的车架号尾号为【"+ clsbdh +"】的【"+ clpp +"】爱车已完成"+ywlx+"业务的的登记受理，请尽快完成业务缴费与选号。缴费方式：查验爱山东查验预约系统推送的缴费二维码信息，长按保存缴费码后，使用支付宝或微信完成线上缴费，或业务大厅综合窗口现场缴费。选号方式：通过12123完成预选号并在业务预约时确认，或到自助机完成选号。";
                break;
            // 受理不通过推送
            case "DE1":
                message = "【机动车查验预约】尊敬的"+username+"用户，您的车架号尾号为【"+ clsbdh +"】的【"+ clpp +"】爱车"+ywlx+"业务登记时出现异常，请到业务大厅导办岗联系处理。";
                break;
            // 制证完成推送(不含号牌)
            case "D07A":
                message = "【机动车查验预约】尊敬的"+username+"用户，您的车架号尾号为【"+ clsbdh +"】的【"+ clpp +"】爱车办理"+ywlx+"业务已完成证件制作，请前往业务大厅发证岗凭预约码领取。欢迎您使用窗口评价器为本次服务进行评价。如需帮助请拨打0532-66572638。";
                break;
            // 取证完成(不含号牌)
            case "D11A":
                message = "【机动车查验预约】尊敬的"+username+"用户，您的车架号尾号为【"+ clsbdh +"】的【"+ clpp +"】爱车办理"+ywlx+"业务，在"+ time +"领取证件，感谢您前来办理车管业务，祝您用车愉快。";
                break;
            // 放入号牌柜完成推送
            case "D11":
                message = "【机动车查验预约】尊敬的"+username+"用户，您的车架号尾号为【"+ clsbdh +"】的【"+ clpp +"】爱车办理"+ywlx+"业务已完成号牌与证件制作，请前往东南侧智能号牌发放柜自助领取，取件码为:"+ hpgkl +"；前往场地内号牌安装处免费安装号牌。请您在智能号牌发放柜为本次服务进行评价，感谢您的满意评价。如需帮助请拨打0532-66572638。";
                break;
            // 取证取牌完成
            case "D13":
                message = "【机动车查验预约】尊敬的"+username+"用户，您的车架号尾号为【"+ clsbdh +"】的【"+ clpp +"】爱车办理"+ywlx+"业务，在"+ time +"领取证件，您可到号牌安装处出示预约二维码免费为您的爱车安装号牌，感谢您前来办理车管业务，祝您用车愉快。";
                break;
            // 爽约推送
            case "AE2":
                message = "【机动车查验预约】尊敬的"+username+"用户，您的车架号尾号为【"+ clsbdh +"】的【"+ clpp +"】爱车预约办理"+ywlx+"业务，未在预约时间到场办理，本次预约后台记录为爽约。提醒：您可在预约当日前申请取消预约，多次爽约会影响您后续的预约服务，感谢您的理解。";
                break;
            // 超时未领取号牌推送
            case "D12":
                message = "【机动车查验预约】尊敬的"+username+"用户,您的车架号尾号为【"+ clsbdh +"】的【"+ clpp +"】爱车预约办理"+ywlx+"业务，请尽快到智能号牌发放柜领取。超过24小时未领取的，请联系智能号牌发放柜的人工窗口领取，谢谢。";
                break;

        }
        return message;
    }

    @RequestMapping("/meslog")
    public Result MessageInfo(){
        Result result = new Result();
        try {
//            QueryWrapper queryWrapper = new QueryWrapper<>();
//            queryWrapper.isNull("sfsc");
//            List<MessageLog> list = messageLogMapper.selectList(queryWrapper);
            List<MessageLog> list = messageLogMapper.selectList();
            if (!list.isEmpty()) {
                result.setCode(200);
                result.setMsg("查询短信内容成功");
                result.setData(list);
                for (MessageLog item : list){
                    item.setSfsc("1");
//                    messageLogMapper.updateById(item);
                    messageLogMapper.updateSfscById(item.getId());
                }
            }else {
                result.setCode(0);
                result.setMsg("无未上传短信内容");
                result.setData(null);
            }
        }catch (Exception e){
            logger.info("短信日志查询异常:"+e.getMessage());
            result.setCode(404);
            result.setMsg("查询异常:"+e.getMessage());
        }
        return result;
    }

    public  String getToken(String userName, String passWord) throws Exception{
        logger.info("访问地址:"+ tokenUrl);
        JSONObject param = new JSONObject();
        param.put("userName", userName);
        param.put("passWord", passWord);

        String token = "0";
//        String response ="{\"success\":true,\"message\":\"登录成功\",\"code\":200,\"result\":{\"token\":\"TOKEN\"},\"timestamp\":1697167195348}";  //HttpUtil.post(tokenUrl, param.toString());
        String response = HttpUtil.post(tokenUrl, param.toString());
        JSONObject obj = JSONObject.parseObject(response);
        /*
         * {"success":true,"message":"登录成功","code":200,"result":{"token":"TOKEN"},"timestamp":1697167195348}
         */
        if (200 == obj.getIntValue("code"))
        {
            JSONObject result = obj.getJSONObject("result");
            token = result.getString("token");
        }

        return token;
    }

    public String sendSms(String token , String phone, String msg, String longid) throws Exception{
        if (token.length() > 1) {
            JSONObject param = new JSONObject();
            param.put("msgContent", msg);
            param.put("phones", phone);
            param.put("longId", longid);

            String id = "0";
//            String response = "{\"success\":true,\"message\":\"发送成功！\",\"code\":200,\"result\":{\"sendIds\":[\"1712669467308507137\"]},\"timestamp\":1697167195482}\n";//HttpUtil.post(sendUrl, token, param.toString());
            String response =HttpUtil.post(sendUrl, token, param.toString());
            logger.info("短信调用返回结果:"+response);
            JSONObject obj = JSONObject.parseObject(response);
            /*
             * {"success":true,"message":"发送成功！","code":200,"result":{"sendIds":["1712669467308507137"]},"timestamp":1697167195482}
             */
            if (200 == obj.getIntValue("code")) {
                JSONObject result = obj.getJSONObject("result");
                // {"sendIds":["1712669467308507137"]}
                JSONArray sendid = result.getJSONArray("sendIds");
                // ["1712669467308507137"]
                id = sendid.getString(0);
                return "发送成功:"+id;
            }
            return response;
        }
        return "token未知:"+token;
    }
}
